using System.Text.RegularExpressions;
using Microsoft.Extensions.Logging;
using Vin.Extension.Email.Service;
using Vin.Extension.LoggerNotify.Options;
using Vin.Extension.LoggerNotify.Tools;
using Vin.Tool.AspNetCore.Singleton;

namespace Vin.Extension.LoggerNotify.Logger.Email;

public class EmailLogger : BaseLogger
{
    private VinEmailService? EmailService => VinApp.GetService<VinEmailService>();

    private EmailNotifyOption EmailNotifyOption => VinApp.GetConfig<EmailNotifyOption>();

    public override void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception,
        Func<TState, Exception?, string> formatter)
    {
        if (exception != null || EmailService == null || !CheckIsNotify(logLevel) ||
            EmailNotifyOption.EnableEmail == false || EmailNotifyOption.Receivers.Count <= 0) return;
        var (title, message, requestId) =
            NotifyTool.RegexMessage(formatter(state, exception), Option.TitleRegex, Option.TitleLength);
        _ = EmailService.SendEmail(EmailNotifyOption.Receivers, $"【{logLevel.ToString()}】 | {title} | 【{requestId}】",
            message, null);
    }
}